package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.thread.UserThreadLocal;
import com.sun.istack.Nullable;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author daxin
 * @date 2022/7/17 8:09
 */
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头伤的userId字段
        String userId = request.getHeader("userId");
        if (StringUtils.isEmpty(userId)) {
            log.warn("用户id为空");
            return false;
        }

        // 不为空 -> 存放到ThreadLocal
        // 1. 创建ThreadLocal类（get、set）
        // 2. 调用ThreadLocal类的set方法，往里面存储数据
        WmUser wmUser = new WmUser();
        wmUser.setId(Integer.parseInt(userId));
        UserThreadLocal.set(wmUser);

        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        // 清除ThreadLocal
        UserThreadLocal.remove();
    }

}
